package com.besttone.search;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import com.aibang.open.client.AibangApi;
import com.aibang.open.client.exception.AibangException;
import com.besttone.search.model.SearchParm;
import com.besttone.search.util.Constants;
import com.besttone.widget.QuickAction;
import com.besttone.widget.QuickActionBar;
import com.besttone.widget.QuickActionWidget;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ColorFilter;
import android.graphics.LightingColorFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.*;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class DetailActivity extends Activity {

	private LinearLayout info;
	private Animation enterAnim;
	private Animation exitAnim;
	private QuickActionWidget mBar;
	private TextView abName;
	private TextView abAddr;
	private TextView abTel;
	private TextView abCost;
	private TextView abCate;
	private TextView abWorkTime;
	private TextView abDesc;
	private ImageView abImg;
	private AibangApi mAibang;
	private String bId;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.poidetail);
		
		Bundle bundle = this.getIntent().getExtras();
		bId = bundle.getString("id");
		
		LayoutInflater inflater = LayoutInflater.from(this);
		info = (LinearLayout) inflater.inflate(R.layout.poiinfo, null);
		mAibang = new AibangApi(Constants.abAppKey);
		try {
			if(NetWorkStatus()) {
				String rtnJson = mAibang.biz(bId);
				
				JSONObject detailJsonObject = new JSONObject(rtnJson);
				JSONObject bizJsonObject = detailJsonObject.getJSONObject("biz");
				String id = (String) bizJsonObject.get("id");
				String name = (String) bizJsonObject.get("name");
				String county = (String) bizJsonObject.get("county");
				String addr = (String) bizJsonObject.get("addr");
				String tel = (String) bizJsonObject.get("tel");
				String cate = (String) bizJsonObject.get("cate");
				String rate = (String) bizJsonObject.get("rate").toString();
				String cost = (String) bizJsonObject.get("cost").toString();
				String desc = (String) bizJsonObject.get("desc");
				String lng = (String) bizJsonObject.get("lng").toString();
				String lat = (String) bizJsonObject.get("lat").toString();
				String workTime =  (String) bizJsonObject.get("work_time");
				String siteUrl = (String) bizJsonObject.get("site_url");
				String imgUrl = (String) bizJsonObject.get("img_url");
				
				abName = (TextView) findViewById(R.id.abName);
				abAddr = (TextView) info.findViewById(R.id.abAddr);
				abTel = (TextView) info.findViewById(R.id.abTel);
				abCost = (TextView) info.findViewById(R.id.text2_renjun_value);
				abCate = (TextView) info.findViewById(R.id.cate);
				abWorkTime = (TextView) info.findViewById(R.id.abWorkTime);
				abDesc = (TextView) info.findViewById(R.id.abDesc);
				abImg = (ImageView) info.findViewById(R.id.imageView1);
				
				abName.setText(name);
				abAddr.setText(addr);
				abTel.setText(tel);
				abCost.setText(cost);
				abCate.setText(cate);
				abWorkTime.setText(workTime);
				if(desc!=null) {
					desc = desc.replaceAll("<BR/>", "\n");
					desc = desc.replaceAll("<br/>", "\n");
					desc = desc.replaceAll("<BR />", "\n");
					desc = desc.replaceAll("<br />", "\n");
				}
				abDesc.setText(desc);
				if(imgUrl!=null && !"".equals(imgUrl)) {
					byte[] data = this.getImgData(imgUrl);
					Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
					abImg.setImageBitmap(bitmap);
				} else {
					Resources res = getResources();
					Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.nopic);
					abImg.setImageBitmap(bmp);
				}

			}
		} catch (Exception e) {
			Log.v("商家详情", "获取商家详情出错");
		}
		

		LinearLayout scroll = (LinearLayout) findViewById(R.id.lite_list);

		LayoutParams layoutParams = new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.WRAP_CONTENT);

		scroll.addView(info, layoutParams);

		prepareQuickActionBar();
		enterAnim = AnimationUtils.loadAnimation(this, R.anim.anim_enter);
		exitAnim = AnimationUtils.loadAnimation(this, R.anim.anim_exit);

//		View btnMore = findViewById(R.id.more);
//		btnMore.setOnClickListener(this);

//		View btnRequest = findViewById(R.id.requestroute);
//		btnRequest.setOnClickListener(this);

	}

	public void onClick(View v) {
		switch (v.getId()) {
//		case R.id.more: {
//			View view = findViewById(R.id.popup_more);
//
//			if (view.getVisibility() == View.VISIBLE) {
//				view.startAnimation(exitAnim);
//				view.setVisibility(View.GONE);
//			} else {
//				view.startAnimation(enterAnim);
//				view.setVisibility(View.VISIBLE);
//			}
//			break;
//		}

//		case R.id.requestroute: {
//			mBar.show(v);
//			break;
//		}

		}

	}

	private void prepareQuickActionBar() {
		this.mBar = new QuickActionBar(this);
		this.mBar.addQuickAction(new MyQuickAction(this, R.drawable.icon_car,
				"自驾"));
		this.mBar.addQuickAction(new MyQuickAction(this, R.drawable.icon_bus,
				"公共交通"));
		this.mBar.addQuickAction(new MyQuickAction(this, R.drawable.icon_walk,
				"步行"));
		// this.mBar.setOnQuickActionClickListener(this.mActionListener);
	}

	private static class MyQuickAction extends QuickAction {
		private static final ColorFilter BLACK_CF = new LightingColorFilter(
				-16777216, -16777216);

		// public MyQuickAction(Context paramContext, int paramInt1, int
		// paramInt2)
		// {
		// super(buildDrawable(paramContext, paramInt1),
		// String.valueOf(paramInt2));
		// }

		public MyQuickAction(Context paramContext, int paramInt,
				CharSequence paramCharSequence) {
			super(paramContext, paramInt, paramCharSequence);
		}

		// private static Drawable buildDrawable(Context paramContext, int
		// paramInt)
		// {
		// Drawable localDrawable =
		// paramContext.getResources().getDrawable(paramInt);
		// localDrawable.setColorFilter(BLACK_CF);
		// return localDrawable;
		// }
	}
	
	private byte[] getImgData(String path) throws Exception {
		byte[] b = null;
		URL url = new URL(path);
		HttpURLConnection http = (HttpURLConnection) url.openConnection();
		http.setConnectTimeout(3000);
		http.setRequestMethod("GET");
		InputStream in = http.getInputStream();
		b = input2byte(in);
		return b;
	}
	
	public static final byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}
	
    private boolean NetWorkStatus() {
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
    	}
//    	if (netSataus) {
//    		Builder b = new AlertDialog.Builder(this).setTitle("没有可用的网络").setMessage("是否对网络进行设置?");
//    		b.setPositiveButton("是", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				Intent mIntent = new Intent("/");
//    				ComponentName comp = new ComponentName("com.android.settings", 
//    						"com.android.settings.WirelessSettings");
//    				mIntent.setComponent(comp);
//    				mIntent.setAction("android.intent.action.VIEW");
//    				startActivityForResult(mIntent,0); // 如果在设置完成后需要再次进行操作，可以重写操作代码，在这里不再重写
//    			}
//    		}).setNeutralButton("否", new DialogInterface.OnClickListener() {
//    			public void onClick(DialogInterface dialog, int whichButton) {
//    				dialog.cancel();
//    			}
//    		}).show();	
//    	}
    	return netSataus;
    }
	
}